package com.ithinks.flow.common.utils.middleware.rabbitMQ.pubsubmode;

import com.ithinks.flow.common.utils.middleware.rabbitMQ.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Description
 * @ClassName Consumer
 * @Author MR.LI
 * @date 2020.11.27 14:54
 */
public class Email_Consumer {

    private static final String EXCHANGE_FANOUT_INFORM = "exchange_fanout_inform";

    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";

    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";

    private static String IP = "localhost";
    //端口
    private static int PORT = 5672;
    //虚拟机IP，默认/
    private static String VHOST = "/";
    //队列名称
    private static String USERNAME = "guest";

    private static String PASSWORD = "guest";

    public static void main(String[] args) throws IOException {
        //1、创建连接
        Connection connection = ConnectionUtils.getConnection(IP,PORT,VHOST,USERNAME,PASSWORD);

        //2、创建通道
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.FANOUT);

        channel.queueDeclare(QUEUE_INFORM_EMAIL,true,false,false,null);

        channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_FANOUT_INFORM,"");

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                long deliveryTag = envelope.getDeliveryTag();
                String exchange = envelope.getExchange();
                String message = new String(body,"UTF-8");
                System.out.println(message);
            }
        };
        //监听队列：参数--队列名称、是否自动恢复，设置为true标识消息接收到自动向mq回复接收到
        //消费消息方法，接收到消息后调用的方法
        channel.basicConsume(QUEUE_INFORM_EMAIL,true,defaultConsumer);
    }
}
